package com.supermap.pisaclient.map;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.supermap.pisaclient.R;
import com.supermap.util.base.BaseFragment;
import com.supermap.util.util.ToastUtil;
import com.supermap.util.view.OnClick;
import com.supermap.util.view.ViewInject;
import com.supermap.util.view.ViewUtils;
import com.supermap.util.widget.EditTextDel;



/**
 * Copyright (C) 2017 北京超图软件股份有限公司 版权所有
 * <p>
 * 功能描述：地图首页 作者：李会林
 * <p>
 * 修改人： 修改描述： 修改日期
 */
public class MapFragment extends BaseFragment implements OnGetGeoCoderResultListener {
    @ViewInject(R.id.search_content)
    private EditTextDel mSearchKey;
    @ViewInject(R.id.map_view)
    private MapView mMapView;//地图的控件
    private BaiduMap mBaiduMap;//百度地图对象
    private MyLocationListener mLocationListener;//重写的监听类
    private LocationClient mLocationClient;
    private String mSearchContent;
    private boolean mIsFirstLocation = true;
    // 搜索模块
    private GeoCoder mSearch;

    @Override
    public View getContainerView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_map, null);
        ViewUtils.inject(this, view);
        return view;
    }

    @Override
    public void initData() {
        //初始化地图
        initMap();
        //初始化定位
        initLocation();
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        mSearchKey.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchContent = mSearchKey.getText().toString().trim();
                    if (!TextUtils.isEmpty(mSearchContent)) {
                        gotoSearch();
                    } else {
                        ToastUtil.showCustomViewToast(mContext, R.string.please_input_keywords);
                    }
                }
                return false;
            }
        });
    }

    private void initMap() {
        // 不显示缩放比例尺
        mMapView.showZoomControls(true);
        // 不显示百度地图Logo
        mMapView.removeViewAt(1);
        //百度地图
        mBaiduMap = mMapView.getMap();
        // 改变地图状态
        MapStatus mMapStatus = new MapStatus.Builder().zoom(15).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    private void initLocation() {
        //定位客户端的设置
        mLocationClient = new LocationClient(mContext);
        mLocationListener = new MyLocationListener();
        //注册监听
        mLocationClient.registerLocationListener(mLocationListener);
        //配置定位
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");//坐标类型
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//打开Gps
        option.setScanSpan(1000);//1000毫秒定位一次
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastUtil.showCustomViewToast(mContext, R.string.not_found_address, Toast.LENGTH_SHORT);
            return;
        }
        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.location_address)));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
                .getLocation()));
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }

    /*
     * 当服务器收到请求并返回结果后，就会回调之前注册的BDLocationListener：
    */
    public class MyLocationListener implements BDLocationListener {
        //定位请求回调函数,这里面会得到定位信息
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //将获取的location信息给百度map
            MyLocationData data = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100)
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(data);
            if (mIsFirstLocation) {
                //获取经纬度
                LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(status);//动画的方式到中间
                mIsFirstLocation = false;
            }
        }
    }

    /**
     * 跳转到搜索的城市
     */
    private void gotoSearch() {
        mSearch.geocode(new GeoCodeOption().city("").address(mSearchContent));
    }


    @Override
    public void onStart() {
        super.onStart();
        //必须主动开启定位功能
        mBaiduMap.setMyLocationEnabled(true);
        //如果定位client没有开启，开启定位
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mSearch.destroy();
        //关闭定位
        mLocationClient.stop();
        // 当不需要定位图层时关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
    }

    @OnClick({R.id.revert_location})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.revert_location:
                mIsFirstLocation = true;
                break;
        }
    }
}
